package com.wwwarehouse.taskcenter.fragment.job_point.step6;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.fragment.CommonBasePagerFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.job_point.AddJobPointStep6ResponseBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;
import com.wwwarehouse.taskcenter.eventbus_event.TaskPointCardEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * @创建者 chenchao.
 * @创建时间 2017/10/25 18:53
 * @描述 ${TODO}
 */

public class ChooseConnectObjectFragment6 extends CommonBasePagerFragment implements View.OnClickListener {

    private Button mBtSave;
    public static final int REQUEST_1 = 1003,REQUEST_CODE = 10004;
    private ArrayList<AddJobPointStep6ResponseBean.ListBean> listBean;
    private Map<String,AddJobPointStep6ResponseBean.ListBean> listBeanMap = new HashMap<>();
    private String jobPointUkid;

    String asc = "create_time asc";
    String desc = "create_time desc";
    String mSort = desc;
    private int mSelectedBubblePosition = 2;
    private String searchKey = "";
    private int total;

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ChooseConnectObjectFragment6) {
            mActivity.setTitle("" + getString(R.string.new_task_step6_title_txt));
        }
    }

    @Override
    public void requestDatas() {
        super.requestDatas();

        jobPointUkid = getArguments().getString("jobPointUkid");

        showConfirmButton();
        setConfirmBtnText("" + getString(R.string.new_task_save));

        mBtSave = (Button) getConfirmBtn();
        mBtSave.setOnClickListener(this);
        mBtSave.setEnabled(false);
        requestHttp();
        EventBus.getDefault().register(this);
        ((BaseCardDeskActivity)mActivity).hideFilterBt();
    }

    private void initPager() {
        Bundle bundle = new Bundle();
        bundle.putString("searchKey" , searchKey);
        bundle.putString("mSort" , mSort);

        try {
            setData(total, 10, "com/wwwarehouse/taskcenter/fragment/job_point/step6/ChooseConnectObjectDetailFragment6", bundle, listBean);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.showErrLog("error:"+e.getMessage());
        }
    }

    @Override
    public void sortClick(View anchor) {

        PopUpUtils.showBubbleInviteSort(mActivity, anchor, mSelectedBubblePosition, new PopUpUtils.OnChoiceListener() {
            @Override
            public void onChoice(int position) {
                mSelectedBubblePosition = position;
                switch (position) {
                    case 2:
                        //倒序
                        mSort = desc;
                        break;
                    case 3:
                        //正序
                        mSort = asc;
                        break;
                    default:
                        break;
                }

                requestHttp();
            }
        }, "",mActivity.getResources().getString(R.string.new_task_step6_time_desc),  mActivity.getResources().getString(R.string.new_task_step6_time_asc));
    }


    @Override
    public void searchNoRealTimeClick(String text) {
        searchKey = text;
        requestHttp();
    }

    @Override
    public void cancelClick() {
        //取消按钮点击
        searchKey = "";
        requestHttp();
    }

    @Override
    public void onRefreshListener() {
        requestHttp();
    }


    @Override
    public void onLoadError(String s) {

    }

    /**
     *  查询四权 分页接口，一个页面请求一次的.
     */
    private void requestHttp() {
        Map<String, Object> map = new HashMap<>();
        /**
         * name		string	@mock=业
         query	分页数据	object
         page		number	@mock=1
         size		number	@mock=10
         sort		string	@mock=
         mSort = "create_time asc":创建时间由远到近
         mSort = "create_time desc":创建时间由近到远
         */
        map.put("name","" + searchKey);
        Map<String , Object> queryMap = new HashMap<>();
        queryMap.put("page","1");
        queryMap.put("size",10);
        queryMap.put("sort","" + mSort);

        map.put("query",queryMap);

        loadData(TaskCenterConstant.URL_ADD_JOBPOINT_STEP6_SEARCH_WAY, map, REQUEST_1);

    }


    @Override
    public void onLoadSuccess(String s, int i) {
        if (REQUEST_1 == i) {
            AddJobPointStep6ResponseBean bean = JSON.parseObject(s, AddJobPointStep6ResponseBean.class);
            listBean = bean.getList();

            total = bean.getTotal();

            initPager();
        }
    }

    @Override
    public void onClick(View v) {
        if (v == mBtSave) {
            saveData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(AddJobPointStep6ResponseBean.ListBean bean) {
        // 含有就删除 不含有添加
        if(listBeanMap.containsKey(bean.getBusinessUnitId())){
            Iterator<Map.Entry<String, AddJobPointStep6ResponseBean.ListBean>> iterator = listBeanMap.entrySet().iterator();
            while (iterator.hasNext()){
                if((""+bean.getBusinessUnitId()).equals(iterator.next().getValue().getBusinessUnitId())){
                    iterator.remove();
                }
            }
        }else{
            listBeanMap.put(""+ bean.getBusinessUnitId(),bean);
        }

        if(listBeanMap.isEmpty()){
            mBtSave.setEnabled(false);
        }else{
            mBtSave.setEnabled(true);
        }
    }

    /**
     * 保存服务对象
     */
    public void saveData(){
        Map<String,Object> map = new HashMap<>();
        try {
            map.put("jobPointUkid",Long.parseLong(jobPointUkid));
        } catch (Exception e) {
            e.printStackTrace();
        }
        ArrayList<AddJobPointStep6ResponseBean.ListBean> lists = new ArrayList<>();
        lists.clear();
        for(String str : listBeanMap.keySet()){
            lists.add(listBeanMap.get(str));
        }
        List<Long> serviceObjects = new LinkedList<>();
        for(AddJobPointStep6ResponseBean.ListBean bean : lists){
            try {
                serviceObjects.add(Long.parseLong(bean.getBusinessUnitId()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        map.put("serviceObjects",serviceObjects);

        NoHttpUtils.httpPost(TaskCenterConstant.URL_ADD_JOBPOINT_STEP6_SAVE,map,myOnresponse,REQUEST_CODE);
        showProgressDialog();
    }

    NoHttpUtils.OnResponseListener myOnresponse = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int i) {
            if("0".equals(commonClass.getCode())){
                TaskPointCardEvent taskPointCardEvent = new TaskPointCardEvent();
                taskPointCardEvent.setFinish6(true);
                EventBus.getDefault().post(taskPointCardEvent);
                popFragment();
            }else{
                toast("" + commonClass.getMsg());
            }
        }
        @Override
        public void onFailed(String s, int i) {
        }
        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };

}
